from rest_framework import serializers
from .models import SSHSession, SSHCommand, SSHConnectionPool


class SSHSessionSerializer(serializers.ModelSerializer):
    """SSH会话序列化器"""
    username = serializers.CharField(source='user.username', read_only=True)
    hostname = serializers.CharField(source='host.hostname', read_only=True)
    host_ip = serializers.CharField(source='host.ip', read_only=True)
    duration_seconds = serializers.SerializerMethodField()

    class Meta:
        model = SSHSession
        fields = [
            'session_id', 'username', 'hostname', 'host_ip', 'client_ip',
            'status', 'start_time', 'end_time', 'last_activity',
            'command_count', 'bytes_sent', 'bytes_received',
            'terminal_width', 'terminal_height', 'is_recorded',
            'duration_seconds'
        ]

    def get_duration_seconds(self, obj):
        """获取会话持续时间（秒）"""
        if obj.duration:
            return obj.duration.total_seconds()
        return None


class SSHCommandSerializer(serializers.ModelSerializer):
    """SSH命令序列化器"""
    session_id = serializers.UUIDField(source='session.session_id', read_only=True)
    username = serializers.CharField(source='session.user.username', read_only=True)
    hostname = serializers.CharField(source='session.host.hostname', read_only=True)

    class Meta:
        model = SSHCommand
        fields = [
            'id', 'session_id', 'username', 'hostname',
            'command', 'output', 'exit_code',
            'start_time', 'end_time', 'duration',
            'command_type', 'is_dangerous'
        ]


class SSHConnectionPoolSerializer(serializers.ModelSerializer):
    """SSH连接池序列化器"""
    hostname = serializers.CharField(source='host.hostname', read_only=True)
    host_ip = serializers.CharField(source='host.ip', read_only=True)

    class Meta:
        model = SSHConnectionPool
        fields = [
            'connection_id', 'hostname', 'host_ip',
            'is_active', 'last_used', 'created_at',
            'use_count', 'error_count'
        ]


class SSHConnectionRequestSerializer(serializers.Serializer):
    """SSH连接请求序列化器"""
    host_id = serializers.IntegerField()
    terminal_width = serializers.IntegerField(default=80, min_value=20, max_value=300)
    terminal_height = serializers.IntegerField(default=24, min_value=10, max_value=100)
    
    def validate_host_id(self, value):
        """验证主机ID"""
        from cmdb.models import Host
        try:
            Host.objects.get(id=value, is_active=True)
        except Host.DoesNotExist:
            raise serializers.ValidationError("主机不存在或已禁用")
        return value


class SSHSessionStatsSerializer(serializers.Serializer):
    """SSH会话统计序列化器"""
    total_sessions = serializers.IntegerField()
    active_sessions = serializers.IntegerField()
    total_commands = serializers.IntegerField()
    unique_hosts = serializers.IntegerField()
    average_session_duration = serializers.FloatField()


class SSHTerminalConfigSerializer(serializers.Serializer):
    """SSH终端配置序列化器"""
    theme = serializers.ChoiceField(choices=['dark', 'light'], default='dark')
    font_size = serializers.IntegerField(default=14, min_value=10, max_value=24)
    font_family = serializers.CharField(default='Monaco, Consolas, monospace')
    cursor_blink = serializers.BooleanField(default=True)
    bell_sound = serializers.BooleanField(default=False)
    scroll_back = serializers.IntegerField(default=1000, min_value=100, max_value=10000)
